<template>
  <div class="content-container">
    <!-- 添加空白区域，使内容向下移但不要太多 -->
    <div class="admin-page-spacer"></div>

    <el-card>
      <!-- 搜索框 -->
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="公告内容">
          <el-input v-model="searchForm.keyword" placeholder="请输入公告内容" clearable />
        </el-form-item>
        <el-form-item label="创建日期">
          <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
        </el-form-item>
        <el-form-item label="是否展示">
          <el-select v-model="searchForm.isDisplayed" placeholder="请选择">
            <el-option label="全部" value="" />
            <el-option label="是" value="true" />
            <el-option label="否" value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchNotices">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 新增公告按钮 -->
      <el-button type="primary" @click="openEditDialog(null)">+ 新增</el-button>

      <!-- 公告列表 -->
      <el-table :data="noticeList">
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="title" label="公告标题" min-width="150" />
        <el-table-column prop="content" label="公告内容" min-width="200">
          <template #default="{ row }">
            <span v-html="row.content"></span>
          </template>
        </el-table-column>
        <el-table-column prop="isDisplayed" label="是否展示" width="100">
          <template #default="{ row }">
            <el-switch v-model="row.isDisplayed" @change="toggleNotice(row)" />
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="发布时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="openEditDialog(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteNotice(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          :current-page="pagination.page"
          :page-size="pagination.pageSize"
          :total="pagination.total"
          layout="total, prev, pager, next"
          @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 编辑/新增公告的弹窗 -->
    <el-dialog v-model="editDialogVisible" :title="editNotice.id ? '编辑公告' : '新增公告'">
      <el-form ref="editFormRef" :model="editNotice" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="editNotice.title" placeholder="请输入公告标题" />
        </el-form-item>
        <el-form-item label="公告内容">
          <el-input v-model="editNotice.content" type="textarea" rows="4" placeholder="请输入公告内容" />
        </el-form-item>
        <el-form-item label="是否展示">
          <el-switch v-model="editNotice.isDisplayed" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveNotice">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { fetchNotices as fetchNoticesAPI, createNotice, updateNotice, deleteNotice as deleteNoticeAPI } from '@/api/admin/notices';

const noticeList = ref([]);
const searchForm = reactive({
  keyword: '',
  dateRange: [],
  isDisplayed: ''
});
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
});
const editDialogVisible = ref(false);
const editNotice = reactive({
  id: null,
  title: '',
  content: '',
  isDisplayed: true
});

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-');
};

// 获取公告数据
const fetchNotices = async () => {
  try {
    // 处理日期范围
    const params = {
      current: pagination.page,
      size: pagination.pageSize
    };

    if (searchForm.keyword) {
      params.content = searchForm.keyword;
    }

    if (searchForm.isDisplayed !== '') {
      params.isDisplayed = searchForm.isDisplayed === 'true';
    }

    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.createdAt = searchForm.dateRange[0];
      params.updatedAt = searchForm.dateRange[1];
    }

    const res = await fetchNoticesAPI(params);
    if (res.success) {
      noticeList.value = res.data.records || [];
      pagination.total = res.data.total || 0;
    } else {
      ElMessage.error(res.message || '获取公告失败');
    }
  } catch (error) {
    console.error('获取公告失败', error);
    ElMessage.error('获取公告失败');
  }
};

// 重置搜索条件
const resetSearch = () => {
  searchForm.keyword = '';
  searchForm.dateRange = [];
  searchForm.isDisplayed = '';
  fetchNotices();
};

// 开关公告状态
const toggleNotice = async (row) => {
  try {
    const res = await updateNotice(row.id, { isDisplayed: row.isDisplayed });
    if (res.success) {
      ElMessage.success('状态更新成功');
    } else {
      ElMessage.error(res.message || '状态更新失败');
      row.isDisplayed = !row.isDisplayed; // 恢复状态
    }
  } catch (error) {
    ElMessage.error('状态更新失败');
    row.isDisplayed = !row.isDisplayed; // 恢复状态
  }
};

// 打开编辑/新增公告弹窗
const openEditDialog = (notice) => {
  if (notice) {
    Object.assign(editNotice, notice);
  } else {
    editNotice.id = null;
    editNotice.title = '';
    editNotice.content = '';
    editNotice.isDisplayed = true;
  }
  editDialogVisible.value = true;
};

// 保存公告
const saveNotice = async () => {
  if (!editNotice.title || !editNotice.title.trim()) {
    return ElMessage.warning('请输入公告标题');
  }
  
  if (!editNotice.content || !editNotice.content.trim()) {
    return ElMessage.warning('请输入公告内容');
  }
  
  try {
    let res;
    if (editNotice.id) {
      res = await updateNotice(editNotice.id, editNotice);
    } else {
      res = await createNotice(editNotice);
    }
    
    if (res && res.success) {
      ElMessage.success(editNotice.id ? '公告更新成功' : '公告新增成功');
      editDialogVisible.value = false;
      fetchNotices();
    } else {
      ElMessage.error(res?.message || '保存失败');
    }
  } catch (error) {
    console.error('保存公告失败', error);
    ElMessage.error('保存失败');
  }
};

// 删除公告
const deleteNotice = async (id) => {
  ElMessageBox.confirm('确认删除该公告吗？', '提示', { type: 'warning' })
      .then(async () => {
        const res = await deleteNoticeAPI(id);
        if (res && res.success) {
          ElMessage.success('删除成功');
          fetchNotices();
        } else {
          ElMessage.error(res?.message || '删除失败');
        }
      })
      .catch(() => {});
};

// 处理分页变化
const handleCurrentChange = (page) => {
  pagination.page = page;
  fetchNotices();
};

// 初始化
onMounted(() => {
  fetchNotices();
});
</script>

<style scoped>
.content-container {
  margin-top: 15px;
}
</style>
